<template>
  <div>
    <el-button type="primary" @click="addTrademark"
      >添加 <i class="el-icon-plus"></i
    ></el-button>
    <el-table
      border
      :data="trademark.records"
      style="width: 100%; margin: 20px 0"
    >
      <el-table-column prop="prop" label="序号" width="80" type="index">
      </el-table-column>
      <el-table-column label="品牌名称" prop="tmName" width="width">
      </el-table-column>
      <el-table-column label="品牌LOGO" width="width">
        <template v-slot="{ row }">
          <img width="100" v-lazy="row.logoUrl" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template v-slot="{ row }">
          <el-button
            @click="updateTramark(row)"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-popconfirm
            confirmButtonText="确定"
            cancelButtonText="取消"
            icon="el-icon-info"
            iconColor="red"
            :title="`确定删除${row.tmName}吗？`"
            @onConfirm="confirm(row)"
          >
            <el-button
              style="margin: 0 20px"
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="text-align: center"
      background
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,total,sizes"
      prev-text="上一页"
      next-text="下一页"
      :total="trademark.total"
      @current-change="currentChange"
      @size-change="sizeChange"
    >
    </el-pagination>

    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="tmForm" :rules="rules" ref="form">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            drag
            ref="upload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let validateTmName = (rule, value, cb) => {
      if (/^\w{4,8}$/.test(value)) {
        cb();
      } else {
        cb(new Error("品牌名称必须4到8位"));
      }
    };
    return {
      page: 1,
      limit: 3,
      trademark: {},
      dialogFormVisible: false,
      tmForm: {
        logoUrl: "",
        tmName: "",
      },
      rules: {
        tmName: [
          { required: true, validator: validateTmName, trigger: "blur" },
        ],
        logoUrl: [{ required: true, message: "请上传图片" }],
      },
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    async getData(pager = 1) {
      this.page = pager;
      let { page, limit } = this;
      let res = await this.$http.trademark.reqTrademark(page, limit);
      // console.log(res);
      if (res.code == 200) {
        this.trademark = res.data;
      }
    },
    currentChange(page) {
      // console.log(page);
      this.getData(page);
    },
    sizeChange(s) {
      this.limit = s;
      this.getData();
    },
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    async addOrUpdateTrademark() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            await this.$http.trademark.reqAddOrUpdateTrademark(this.tmForm);
            this.dialogFormVisible = false;
            this.getData(this.tmForm.id ? this.page : 1);
            this.$message({
              message: this.tmForm.id ? "恭喜你，修改成功" : "恭喜你，添加成功",
              type: "success",
            });
          } catch (error) {
            this.$message({
              message: this.tmForm.id ? "遗憾，修改失败" : "遗憾，添加失败",
              type: "error",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addTrademark() {
      this.dialogFormVisible = true;
this.tmForm = {
          logoUrl: "",
          tmName: "",
        };
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
        this.$refs.form.resetFields();
        
      });
    },
    updateTramark(row) {
      this.dialogFormVisible = true;

      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
        this.$refs.form.resetFields();
        this.tmForm = { ...row };
      });
    },
    async confirm(row) {
      try {
        await this.$http.trademark.reqDeleteTrademark(row.id);
        let page =
          this.trademark.records.length > 1 ? this.page : this.page - 1;
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.getData(page);
      } catch (error) {}
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>